package com.kangyi.user.interceptor;

import com.kangyi.constant.JwtClaimsConstant;
import com.kangyi.constant.MessageConstant;
import com.kangyi.context.BaseContext;
import com.kangyi.exception.TokenException;
import com.kangyi.properties.JwtProperties;
import com.kangyi.user.service.Impl.TokenBlacklistServiceImpl;
import com.kangyi.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Blank
 * @version 1.0
 * jwt令牌校验的拦截器
 */
@Component
@Slf4j
public class JwtTokenUserInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private TokenBlacklistServiceImpl tokenBlacklistServiceImpl;
    /**
     * 校验jwt
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        System.out.println("当前线程的id："+ Thread.currentThread().getId());


        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }

        //1、从请求头中获取令牌
        String token = request.getHeader(jwtProperties.getUserTokenName());

        if (token == null) {
            log.warn("请求中缺少Token");
            response.setStatus(401);
            throw new TokenException(MessageConstant.TOKEN_LACK);
        }


        try {
            // 解析 JWT
            Claims claims = JwtUtil.parseJWT(jwtProperties.getUserSecretKey(), token);
            String jti = claims.getId(); // 获取 jti
            log.info("解析出的 jti: {}", jti);

            // 检查 token 是否在黑名单中
            if (tokenBlacklistServiceImpl.isTokenBlacklisted(jti)) {
                log.warn("Token 已失效: {}", jti);
                response.setStatus(401);
                throw new TokenException(MessageConstant.TOKEN_EXPIRED_PLEASE_LOG_IN_AGAIN);
            }

            // 获取用户 ID
            Object userIdObj = claims.get(JwtClaimsConstant.USER_ID);
            if (userIdObj == null) {
                log.error("JWT 中缺少 userId");
                response.setStatus(401);
                throw new TokenException("Token 缺少 userId 信息");
            }

            Integer userId = Integer.valueOf(userIdObj.toString());
            log.info("JWT 校验通过，当前用户 ID: {}", userId);
            BaseContext.setCurrentId(userId);

            return true;
        } catch (Exception ex) {
            log.error("JWT 校验失败: {}", ex.getMessage(), ex);
            response.setStatus(401);
            throw new TokenException(MessageConstant.TOKEN_IS_INVALID_OR_EXPIRED);
        }

    }
}
